package org.idea.spring.ioc.javabeans;

import org.idea.spring.ioc.bean.Person;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyEditorSupport;
import java.util.stream.Stream;

/**
 * @Author idea
 * @Date created in 9:38 下午 2020/4/22
 */
public class PropertyDescriptDemo {

    public static void main(String[] args) throws IntrospectionException {
        //这里可以按照不同的层次去获取bean的属性内容
        BeanInfo personBean = Introspector.getBeanInfo(Person.class,Object.class);
        Stream.of(personBean.getPropertyDescriptors())
                .forEach(propertyDescriptor ->{
                    Class<?> clazz = propertyDescriptor.getPropertyEditorClass();
                    String propertyName = propertyDescriptor.getName();
                    if("age".equals(propertyName)){
                        propertyDescriptor.setPropertyEditorClass(String2IntegerPropertyEditor.class);
                        propertyDescriptor.createPropertyEditor(personBean);
                    }
                    System.out.println(propertyDescriptor);
                });

    }

    static class String2IntegerPropertyEditor extends PropertyEditorSupport {

        @Override
        public void setAsText(String text) throws java.lang.IllegalArgumentException {
            Integer val =  Integer.valueOf(text);
            setValue(val);
        }
    }
}
